import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:library_base/base/base_state_config.dart';
import 'package:library_base/base/base_state_ui.dart';
import 'package:library_base/base/base_widget_lifecycle.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/log/fb_log.dart';
import 'package:library_base/network/http_util.dart';
import 'package:library_base/provider/base_controller.dart';
import 'package:library_base/route/app_analysis.dart';
import 'package:library_base/utils/theme_util.dart';

abstract class BaseState<T extends StatefulWidget, C extends BaseController> extends State<T>
    with
        BasePageUI,
        WidgetsBindingObserver,
        RouteAware,
        BaseWidgetLifeCycle,
        AutomaticKeepAliveClientMixin {
  C? baseGetxController;

  /// 页面的主要Controller
  C? registerController();

  ///状态栏文字是否黑色
  bool statusBarFontIsDark = true;

  @override
  void initState() {
    super.initState();
    ///第一次渲染完毕的时候回调
    WidgetsBinding.instance?.addPostFrameCallback(_frameCallback);
    _initStatusBarFontColor();
    registerSetStateCalBack(() {
      if (mounted) {
        setState(() {});
      }
    });
    onCreate();
  }

  ///第一次渲染完毕的时候会调用这个
  void _frameCallback(Duration timeStamp) {
    baseGetxController?.requestData();
    frameCallback(timeStamp);
  }

  void frameCallback(Duration timeStamp) {}

  ///初始化状态栏文字颜色
  _initStatusBarFontColor() {
    setBarFontColor(isDark: statusBarFontIsDark);
  }

  @override
  void dispose() {
    super.dispose();
    _onDestroy();
  }



  @override
  Widget build(BuildContext context) {
    if (wantKeepAlive) {
      super.build(context);
    }
    if (!isBuild()) {
      _init();
    }
    if (baseGetxController == null) {
      baseGetxController = registerController();
      baseGetxController?.baseState = this;
      baseGetxController?.onCreate();
      controllerOnCreate();
    }
    return uiBuild(context, model: baseGetxController);
  }

  void _init() {
    if (isListenLifeCycle()) {
      try {
        WidgetsBinding.instance?.addObserver(this);
        routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
      } catch (e) {
        logger.e('AppState---->WidgetsBindingObserver或RouteAware监听绑定失败;异常 = $e');
      }
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        //进入应用时候不会触发该状态
        //应用程序处于可见状态,并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume。
        logger.i('AppState---->AppLifecycleState.resumed');
        _onResume();
        break;

      case AppLifecycleState.inactive:
      case AppLifecycleState.paused:
        //应用程序处于不可见状态
        isInFront = false;
        _onPause();
        logger.i('AppState---->AppLifecycleState.paused');
        break;

        case AppLifecycleState.detached:
        //当前页面即将退出
        _onDestroy();
        logger.i('AppState---->AppLifecycleState.detached');
        break;

      default:
        logger.i('AppState---->AppLifecycleState=$state');
        break;
    }
  }

  void _onPause() {
    if (isInFront) {
      isInFront = false;
      baseGetxController?.onPause();
      onPause();
    }
  }

  @override
  bool get wantKeepAlive => false;

  ///当前系统改变了一些访问性活动的回调
  @override
  void didChangeAccessibilityFeatures() {
    super.didChangeAccessibilityFeatures();
    logger.i("AppState---->执行 didChangeAccessibilityFeatures");
  }

  ///低内存回调
  @override
  void didHaveMemoryPressure() {
    super.didHaveMemoryPressure();
    logger.i("AppState---->执行 didHaveMemoryPressure");
  }

  ///用户本地设置变化时调用，如系统语言改变
  @override
  void didChangeLocales(List<Locale>? locale) {
    super.didChangeLocales(locale);
    logger.i("AppState---->执行 didChangeLocales");
  }

  ///应用尺寸改变时回调，例如旋转
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    Size size = WidgetsBinding.instance?.window.physicalSize ?? const Size(0.0, 0.0);
    logger.i("AppState---->执行didChangeMetrics(), didChangeMetrics-宽${size.width},高=${size.height}");
  }

  @override
  Future<bool> didPopRoute() {
    logger.i('AppState---->执行didPopRoute'); //页面弹出
    return Future.value(false); //true为拦截，false不拦截
  }

  @override
  Future<bool> didPushRoute(String route) {
    logger.i('AppState---->执行PushRoute');
    return Future.value(true);
  }

  @override
  Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
    logger.i('AppState---->执行didPushRouteInformation');
    return Future.value(true);
  }

  /// 文字大小改变时候的监听
  @override
  void didChangeTextScaleFactor() {
    logger.i(
        "AppState---->执行didChangeTextScaleFactor:${WidgetsBinding.instance?.window.textScaleFactor}");
  }

  @override
  void didChangePlatformBrightness() {
    final window = WidgetsBinding.instance?.window;
    final brightness = window?.platformBrightness;
    // Brightness.light 亮色
    // Brightness.dark 暗色
    logger.i('AppState---->平台主题改变----didChangePlatformBrightness$brightness');
    // window.onPlatformBrightnessChanged = () {
    //   // This callback gets invoked every time brightness changes
    //   final brightness = window.platformBrightness;
    //   logger.i('YM----平台亮度改变----didChangePlatformBrightness$brightness');
    // };
  }

  /// Called when the top route has been popped off, and the current route
  /// shows up.
  @override
  void didPopNext() {
    logger.i('AppState---->执行didPopNext()');
    isInFront = true;
    _onResume();
  }

  void _onResume() {
    if (isInFront) {
      onResume();
      baseGetxController?.onResume();
    }
  }

  @override
  void onResume() {
    super.onResume();
    _initStatusBarFontColor();
  }

  void _onDestroy() {
    if (isListenLifeCycle()) {
      try {
        routeObserver.unsubscribe(this);
      } catch (e) {
        logger.e('AppState---->RouteAware移除监听失败;异常 = $e');
      }
      try {
        Future.microtask(() {
          WidgetsBinding.instance?.removeObserver(this); //销毁
        });
      } catch (e) {
        logger.e('AppState---->WidgetsBindingObserver移除监听失败;异常 = $e');
      }
    }
    appBarControl.dispose();
    mBaseProvide?.dispose();
    //todo 取消网络
    FBHttpUtil.cancelRequest(context);
    onDestroy();
  }

  /// Called when the current route has been pushed.
  @override
  void didPush() {
    logger.i('AppState---->执行didPush()');
  }

  /// Called when the current route has been popped off.
  @override
  void didPop() {
    super.didPop();
    //防止返回上一个页面时如果页面有TextField时会重新获取焦点导致键盘弹出的问题
    FocusManager.instance.primaryFocus?.unfocus();
    logger.i('AppState---->执行didPop()');
  }

  /// Called when a new route has been pushed, and the current route is no
  /// longer visible.
  @override
  void didPushNext() {
    logger.i('AppState---->执行didPushNext()');
    isInFront = false;
    _onPause();
  }

  void controllerOnCreate() {}
}
